﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
using System.Windows.Forms;
using System.IO;

namespace SharedLib.WinFormMVCFramework.ExceptionHandling
{
    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class UIExceptionHandler : IExceptionHandler
    {
        public UIExceptionHandler(NameValueCollection ignore)
        {
        }

        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            ShowThreadExceptionDialog(exception, handlingInstanceId);
            return exception;
        }

        // Creates the error message and displays it.
        private void ShowThreadExceptionDialog(Exception ex, Guid handlingInstanceId)
        {
            string errorMsg = "The following exception was caught by the Global Exception Handler:"
                            + Environment.NewLine + Environment.NewLine;

            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);

            UIExceptionFormatter formatter = new UIExceptionFormatter(writer, ex, handlingInstanceId);
            // Format the exception.
            formatter.Format();

            errorMsg += sb.ToString();

            ExceptionForm.Show(errorMsg, "Application Error");
        }
    }

}
